package guda.house.web.action.bill;

import guda.grape.autogen.common.page.BizResult;
import guda.grape.util.RequestUtil;
import guda.house.biz.BillExtBiz;
import guda.house.biz.beans.vo.BillExtVO;
import guda.house.biz.beans.vo.BillExtXlsVO;
import guda.house.biz.beans.vo.BillPayXlsVO;
import guda.house.biz.beans.vo.JsonResult;
import guda.house.biz.constants.CommonResultCode;
import guda.house.biz.enums.BillCatEnum;
import guda.house.biz.enums.BooleanEnum;
import guda.house.biz.form.bill.BillDepositSearchForm;
import guda.house.biz.form.bill.BillPaySearchForm;
import guda.house.biz.query.BillDepositQuery;
import guda.house.biz.query.BillPayQuery;
import guda.house.biz.security.AppUtil;
import guda.house.biz.util.ErrorCode;
import guda.house.biz.util.ExportExcelUtil;
import guda.house.biz.util.PriceUtil;
import guda.house.dal.dataobject.BillExtDO;
import guda.house.dal.dataobject.BillPayDO;
import guda.house.dal.dataobject.VillageDO;
import guda.house.web.helper.ResponseHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by well on 15/11/16.
 */
@Controller
@RequestMapping(value = "bill/deposit")
public class DepositAction {

    @Autowired
    private BillExtBiz billExtBiz;

    @RequestMapping(value = "list.htm", method = RequestMethod.GET)
    public String list(HttpServletRequest request, ModelMap modelMap, BillDepositSearchForm billDepositSearchForm) {
        int pageId = RequestUtil.getInt(request, "pageNo");
        int pageSize = RequestUtil.getInt(request, "pageSize");
        if(billDepositSearchForm.getVillageId() == null) {
            List<Long> villageIdList = AppUtil.getVillageIdList();
            if (villageIdList.size() > 0) {
                billDepositSearchForm.setVillageId(villageIdList.get(0));
            }
        }
        BillDepositQuery billDepositQuery = new BillDepositQuery();
        billDepositQuery.setPageNo(pageId);
        billDepositQuery.setPageSize(pageSize);
        billDepositQuery.setSuiteId(billDepositSearchForm.getSuiteId());
        billDepositQuery.setVillageId(billDepositSearchForm.getVillageId());
        billDepositQuery.setBuildingId(billDepositSearchForm.getBuildingId());
        billDepositQuery.setUnitId(billDepositSearchForm.getUnitId());
        billDepositQuery.setBillCat(BillCatEnum.deposit.getDesc());
        modelMap.put("query", billDepositQuery);
        BizResult bizResult = billExtBiz.queryDepositList(billDepositQuery);
        BizResult bizResult1 = billExtBiz.initSearchForm(billDepositSearchForm);
        modelMap.putAll(bizResult1.data);
        if (bizResult.success) {
            modelMap.putAll(bizResult.data);
            return "bill/deposit/list.vm";
        } else {
            return "redirect:/error.htm?code=" + bizResult.code;
        }
    }

    @RequestMapping(value = "refund.htm")
    public void refund(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {
        long refundId = RequestUtil.getLong(request, "refundId");
        JsonResult result = JsonResult.getInstance();
        if (refundId == 0) {
            result.setErrMsg(ErrorCode.getMessage(CommonResultCode.PARAM_MISS));
            ResponseHelper.ajaxReturn(result.getMap(), response);
            return;
        }
        BizResult refund = billExtBiz.refund(refundId);
        if (refund.success) {
            ResponseHelper.ajaxReturn(result.getMap(), response);
            return;
        } else {

            result.setErrMsg(ErrorCode.getMessage(CommonResultCode.UNKOWN_ERROR));
            ResponseHelper.ajaxReturn(result.getMap(), response);
            return;
        }


    }

    @RequestMapping(value = "reverse.htm")
    public void reverse(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {
        long refundId = RequestUtil.getLong(request, "id");
        JsonResult result = JsonResult.getInstance();
        if (refundId == 0) {
            result.setErrMsg(ErrorCode.getMessage(CommonResultCode.PARAM_MISS));
            ResponseHelper.ajaxReturn(result.getMap(), response);
            return;
        }
        BizResult refund = billExtBiz.reverse(refundId);
        if (refund.success) {
            ResponseHelper.ajaxReturn(result.getMap(), response);
            return;
        } else {

            result.setErrMsg(ErrorCode.getMessage(CommonResultCode.UNKOWN_ERROR));
            ResponseHelper.ajaxReturn(result.getMap(), response);
            return;
        }


    }

    @RequestMapping(value = "export.do", method = RequestMethod.GET)
    public void export(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap, BillDepositSearchForm billDepositSearchForm) {

        String filedisplay = null;
        try {
            filedisplay = URLEncoder.encode("押金缴费记录.xls", "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        response.setContentType("application/x-download; charset=UTF-8");
        response.addHeader("Content-Disposition", "attachment; filename=" + filedisplay);

        BillDepositQuery billDepositQuery = new BillDepositQuery();
        billDepositQuery.setPageSize(10000);
        billDepositQuery.setSuiteId(billDepositSearchForm.getSuiteId());
        billDepositQuery.setVillageId(billDepositSearchForm.getVillageId());
        billDepositQuery.setBuildingId(billDepositSearchForm.getBuildingId());
        billDepositQuery.setUnitId(billDepositSearchForm.getUnitId());
        billDepositQuery.setBillCat(BillCatEnum.deposit.getDesc());
        BizResult bizResult = billExtBiz.queryDepositList(billDepositQuery);
        List<BillExtVO> billExtVOList = (List<BillExtVO>)bizResult.data.get("billExtVOList");
        List<BillExtXlsVO> billExtXlsVOList = new ArrayList<BillExtXlsVO>(billExtVOList.size());
        for(BillExtVO billExtVO:billExtVOList){
            BillExtXlsVO billExtXlsVO = new BillExtXlsVO();
            VillageDO villageBySuiteId = AppUtil.getVillageBySuiteId(billExtVO.getBillExtDO().getSuiteId());
            Long deposit = AppUtil.countDeposit(billExtVO.getBillPayDO().getPayTypeId(),villageBySuiteId.getVillageId(),billExtVO.getBillExtDO().getPayTotal());
            billExtXlsVO.setDeposit(PriceUtil.formatCNY(deposit));
            billExtXlsVO.setMoney(PriceUtil.formatCNY(billExtVO.getBillExtDO().getPayTotal()));

            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            billExtXlsVO.setPayTime(simpleDateFormat.format(billExtVO.getBillExtDO().getGmtCreate()));
            billExtXlsVO.setPayWay(billExtVO.getBillPayDO().getPayType());

            billExtXlsVO.setSuiteName(getSuiteName(billExtVO.getBillExtDO().getSuiteId()));
            billExtXlsVO.setIsRefund(BooleanEnum.getByVal(billExtVO.getBillExtDO().getIsRefund()).getDesc());
            billExtXlsVO.setBillType(billExtVO.getBillPayDO().getPayType());
            billExtXlsVOList.add(billExtXlsVO);
        }
        String[] headers = new String[]{"房号","押金金额(元)","缴费类型","支付方式","手续费(元)","缴费时间","是否退款"};
        String[] fields = new String[]{"suiteName","money","billType","payWay","deposit","payTime","isRefund"};
        ServletOutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            ExportExcelUtil.exportExcel("押金缴费记录", headers, fields, billExtXlsVOList, outputStream);
            outputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private String getSuiteName(Long suiteId){
        String villageName = AppUtil.getVillageBySuiteId(suiteId).getVillageName();
        String buildingName = AppUtil.getBuildingBySuiteId(suiteId).getBuildingName();
        String unitName = AppUtil.getUnitBySuiteId(suiteId).getUnitName();
        String suiteName = AppUtil.getSuiteBySuiteId(suiteId).getSuiteName();
        StringBuilder buf = new StringBuilder();
        buf.append(villageName).append(buildingName).append("(幢)").append(unitName).append("(单元)")
                .append(suiteName).append("(房号)");
        return buf.toString();
    }
}
